<?php

/**
 * openid转换接口
 * Date: 2019/06/28
 */

namespace Lib\Service;

use Lib\Base\HttpRequest;
use Lib\Base\Request;
use Lib\Base\L5;
use Lib\Base\Validate;

class TransOpenId
{
    public function __construct()
    { }
    /**
     * 2个不同业务之间openid互转
     * @param string|array $openidList 带转换的openid，可以是单个字符串或者一位数组（数字索引，0开始）
     * @param string $targetAppid 要转换的目标业务的appid
     * @param string  $appName 接口转换申请的应用名称
     * @return array|bool 失败返回false，成功返回转换之后的openid对应关系列表
     * Array
     * (
     *       [0] => Array
     *          (
     *               [source_openid] => o6_bmjrPTlm6_2sgVt7hMZOPfL2M
     *               [target_openid] => o8m9FuCk1a21fL1YUutu_MjhuQtQ
     *           )
     *
     *       [1] => Array
     *          (
     *               [source_openid] => o6_bmjpDo9228S4fSZnJSvldABQI
     *               [target_openid] => o8m9FuAX_NnIC7lhoZeNajP3_GtE
     *           )
     * )
     */
    public function openid2Openid($openidList, $targetAppid, $appName)
    {
        if (Request::serverParam('PROXYNAME')) {
            $url = 'http://proxy-yxgw-comm:12361/innerapi/acctapi/transid/openid_to_openid?appname=' . $appName;
        } else {
            $l5 = L5::getHostInfo(64028801, 65536);
            if (!$l5) {
                return false;
            }
            $url = 'http://' . $l5['hostIp'] . ':' . $l5['hostPort'] . '/innerapi/acctapi/transid/openid_to_openid?appname=' . $appName;
        }

        $postData = [];
        $postData['target_appid'] = $targetAppid;
        if (is_string($openidList)) {
            $postData['openid_list'][] = $openidList;
        } else {
            $postData['openid_list'] = $openidList;
        }

        recordLog("openid2Opneid request url=" . $url . ', data=' . var_export($postData, true), __FILE__, __LINE__);

        $res = (new HttpRequest())->post($url, json_encode($postData));
        if ($res['ret'] != '0') {
            return false;
        }
        $res = $res['data'];
        if (isset($res['openid_list'])) {
            return $res['openid_list'];
        }
        return false;
    }

    /**
     * QQ号转Openid
     * @param int $uin,要转的QQ号
     * @param int $appId,要转换的业务appid
     * @return string|bool 成功则返回转换之后的openid，失败则返回false
     */
    public function uin2Openid($uin, $appId)
    {
        if (!Validate::checkAppid($appId, 'qq')) {
            recordLog('appid错误！appid=' . var_export($appId, true), __FILE__, __LINE__, LP_ERROR);
            return false;
        }

        if (!Validate::checkQQ($uin)) {
            recordLog('QQ号错误！qq=' . var_export($uin, true), __FILE__, __LINE__, LP_ERROR);
            return false;
        }

        try {
            $u2o = new \OIDBOpenInfo(null);
            return $u2o->Uin2OpenID($uin, $appId);
        } catch (\Exception $e) {
            recordLog('QQ号转openid失败，错误消息：' . $e->getMessage(), __FILE__, __LINE__, LP_ERROR);
            return false;
        }
    }

    /**
     * 手Q的openid转QQ号
     * @param string $openid 要转换成QQ号的openid
     * @param int $appId 业务appid
     * @return int|bool 成功则返回对应的QQ号，失败返回false
     */
    public function Openid2Uin($openid, $appId)
    {
        if (!Validate::checkOpenid($openid, 'qq')) {
            recordLog('openid错误！openid=' . var_export($openid, true), __FILE__, __LINE__, LP_ERROR);
            return false;
        }

        if (!Validate::checkAppid($appId, 'qq')) {
            recordLog('appid错误！appid=' . var_export($appId, true), __FILE__, __LINE__, LP_ERROR);
            return false;
        }
        try {
            $u2o = new \OIDBOpenInfo(null);
            return $u2o->OpenID2Uin($openid, $appId);
        } catch (\Exception $e) {
            recordLog('openid转QQ号失败，错误消息：' . $e->getMessage(), __FILE__, __LINE__, LP_ERROR);
            return false;
        }
    }

    /**
     * 手Q不同业务之间openid转换
     * @param string $sourceOpenid 待转换的openid
     * @param int $sourceAppId 待转换业务的appid
     * @param int $targetAppId 目标业务的appid
     * @return string|false 转换之后的openid（与$targetAppId业务相对应的openid）
     */
    public function sqOpenid2Openid($sourceOpenid, $sourceAppId, $targetAppId)
    {
        if (!Validate::checkOpenid($sourceOpenid, 'qq')) {
            recordLog('待转换业务openid错误！openid=' . var_export($sourceOpenid, true), __FILE__, __LINE__, LP_ERROR);
            return false;
        }

        if (!Validate::checkAppid($sourceAppId, 'qq')) {
            recordLog('待转换业务appid错误！appid=' . var_export($sourceAppId, true), __FILE__, __LINE__, LP_ERROR);
            return false;
        }

        if (!Validate::checkAppid($targetAppId, 'qq')) {
            recordLog('目标业务appid错误！appid=' . var_export($targetAppId, true), __FILE__, __LINE__, LP_ERROR);
            return false;
        }
        //先将openid转成QQ号
        $uin = $this->Openid2Uin($sourceOpenid, $sourceAppId);
        if ($uin !== false) {
            //将QQ号转成openid
            return $this->uin2Openid($uin, $targetAppId);
        }
        return false;
    }
}
